package praca.framework;

import java.util.ArrayList;
import java.util.List;

public class ObjectPool<T> {
	
	final private int NR_OF_OBJECTS;
	List<T> pool = new ArrayList<T>();
	ObjectFactory<T> factory;
	
	public interface ObjectFactory<T>{
		public T createObject();
	}
	
	public ObjectPool(ObjectFactory<T> factory, int size){
		NR_OF_OBJECTS=size;	
		this.factory = factory;
	}

	
	public T getObject(){
		T object = null;
		
		if(pool.isEmpty()){//jak jest pusta to tworzymy nowy obiekt
			object = factory.createObject();
		}else{
			object = pool.remove(pool.size()-1);
		}
		return object;
	}
	
	public void free(T obj){
		if(pool.size() <= NR_OF_OBJECTS){
			pool.add(obj);
		}
	}
	
}
